<template>
  <el-button type="text" v-on:click="cancelPage">
    <el-icon style="cursor: pointer"><DArrowLeft /></el-icon>
    {{text.htmlBtnBack}}
  </el-button>
  <el-form
      ref="ruleFormRef"
      :model="ruleForm"
      :rules="rules"
      class="demo-ruleForm"
      status-icon
      style="margin-top: 6px"
  >
    <div style="padding: 6px">
      <el-form-item :label="text.labelTitle" prop="title">
        <el-input v-model="ruleForm.title" style="width: 260px" @change="needSave = true" />
      </el-form-item>
    </div>
    <div style="padding: 6px">
      <div ref="divRef" style="height: 360px"></div>
    </div>
    <el-form-item label-width="160px">
      <el-button type="primary" @click="save">{{ text.labelConfirm }}</el-button>
      <el-button @click="cancelPage">{{ text.labelCancel }}</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import { DArrowLeft } from '@element-plus/icons-vue'
import { AiEditor } from "aieditor"
import "aieditor/dist/style.css"
import StringUtils from "@/utils/StringUtils"
import DefaultMessageHandler from "@/utils/DefaultMessageHandler"
import WeirdService from "@/service/WeirdService"

export default {
  name: 'WeirdForm',
  components: {
    DArrowLeft
  },
  data() {
    return {
      formSize: 'small',
      ruleForm: {
        title: '',
        content: ''
      },
      rules: {
        title: [
          { required: true, message: chrome.i18n.getMessage("commonAlertTitle"), trigger: 'blur' }
        ],
        content: [
          { required: true, message: chrome.i18n.getMessage("commonAlertContent"), trigger: 'blur' }
        ]
      },

      load: false,
      needSave: false,
      hadDraft: false,

      text: {
        labelTitle: chrome.i18n.getMessage("commonLabelTitle"),
        labelConfirm: chrome.i18n.getMessage("commonBtnConfirm"),
        labelCancel: chrome.i18n.getMessage("commonBtnCancel"),
        labelContent: chrome.i18n.getMessage("commonLabelContent"),
        htmlBtnBack: chrome.i18n.getMessage("commonBtnBack")
      },
      contentRef: null
    }
  },
  props: {
    args: {
      type: Object,
      default: () => {
        return {}
      }
    }
  },
  methods: {
    /**
     * 发布.
     */
    save() {
      this.$refs.ruleFormRef.validate((valid) => {
        if (valid) {
          const content = this.contentRef.getHtml()
          if (StringUtils.isBlank(content) || content==='<p></p>') {
            this.$message.error(chrome.i18n.getMessage("commonAlertContent"))
            return
          }
          let fn = 'saveWeird'
          const data = Object.assign({}, this.ruleForm)
          data.content = content
          if (data.id) {
            fn = 'modifyWeird'
          } else {
            delete data.id
          }
          WeirdService[fn](data, (data) => {
            WeirdService.delDraft()
            this.$message.success(chrome.i18n.getMessage("commonAlertSaveSuccess"))
            this.$emit('goPage', 'weird', {})
          }, (fail) => {
            DefaultMessageHandler.error(fail, this)
          })
        } else {
          console.log(this.ruleForm.content)
          return false;
        }
      });
    },
    cancelPage() {
      this.load = false
      this.$emit('goPage', 'weird', {})
    },
    /**
     * 自动保存.
     */
    autoSave() {
      if (this.needSave) {
        WeirdService.saveDraft({
          title: this.ruleForm.title,
          content: this.contentRef.getHtml()
        })
        this.needSave = false
      }
      setTimeout(() => {
        if (this.load) {
          this.autoSave()
        }
      }, 2000)
    },
    /**
     * 加载草稿.
     */
    loadDraft() {
      WeirdService.getDraft((data) => {
        console.log('get draft: ', data)
        if (data) {
          this.$confirm(
              chrome.i18n.getMessage("weirdAlertLoadDraft"),
              chrome.i18n.getMessage("commonTextAlert"),
              {
                confirmButtonText: chrome.i18n.getMessage("commonBtnConfirm"),
                cancelButtonText: chrome.i18n.getMessage("commonBtnCancel"),
                type: 'warning'
              }
          ).then(() => {
            this.ruleForm.title = data.title
            this.contentRef.destroy()
            this.contentRef = new AiEditor({
              element: this.$refs.divRef,
              placeholder: chrome.i18n.getMessage("commonAlertContent"),
              toolbarSize: 'small',
              content: data.content,
              toolbarKeys: ["undo", "redo", "brush", "eraser",
                "|", "heading", "font-family", "font-size",
                "|", "fullscreen"
              ],

              onChange: (content) => {
                console.log('had change content')
                this.needSave = true
              }
            })
          }).catch((cancel) => {
            console.log('cancel: ', cancel)
            if (cancel === 'cancel') {
              WeirdService.delDraft()
            }
          })
        }
      })
    }
  },
  mounted() {
    console.log('args: ', this.args)
    this.ruleForm = Object.assign({
      id: null,
      title: '',
      content: ''
    }, this.args)
    this.contentRef = new AiEditor({
      element: this.$refs.divRef,
      placeholder: chrome.i18n.getMessage("commonAlertContent"),
      toolbarSize: 'small',
      content: this.ruleForm.content,
      toolbarKeys: ["undo", "redo", "brush", "eraser",
        "|", "heading", "font-family", "font-size",
        "|", "fullscreen"
      ],

      onChange: (content) => {
        console.log('had change content')
        this.needSave = true
      }
    })
    this.load = true
    this.autoSave()
    setTimeout(() => {
      this.loadDraft()
    }, 500)
  },
  unmounted() {
    this.load = false
  }
}
</script>

<style scoped>

</style>